4-2 创建订单接口dto对入参数进行校验
DTO 定义
创建 create-wechat-order.dto.ts,对用户传入的参数进行校验:
import {
IsNotEmpty,
IsString,
IsOptional,
ValidateNested,
IsNumber,
} from 'class-validator';
import { Type } from 'class-transformer';
import { Type as TransformType } from 'class-transformer';
class AmountDto {
@IsNotEmpty()
@IsNumber()
total: number;
@IsOptional()
@IsString()
currency?: string;
}
class PayerDto {
@IsNotEmpty()
@IsString()
openid: string;
}
export class CreateWechatOrderDto {
@IsNotEmpty()
@IsString()
description: string;
@IsOptional()
@IsString()
attach?: string;
@IsNotEmpty()
@ValidateNested()
@Type(() => AmountDto)
amount: AmountDto;
@IsNotEmpty()
@ValidateNested()
@Type(() => PayerDto)
payer: PayerDto;
// 可选字段:覆盖服务端默认生成的值
@IsOptional()
@IsString()
time_expire?: string;
@IsOptional()
@IsString()
out_trade_no?: string;
}
typescript
Controller 中使用 DTO
import { Controller, Post, Body } from '@nestjs/common';
import { PayService } from './pay.service';
import { CreateWechatOrderDto } from './dto/create-wechat-order.dto';
@Controller('pay')
export class PayController {
constructor(private readonly payService: PayService) {}
@Post('order')
createOrder(@Body() dto: CreateWechatOrderDto) {
return this.payService.wechatJsPay(dto);
}
@Post('notify')
notify(@Body() body: any) {
console.log('支付通知:', body);
return 'OK';
}
}
typescript
参数校验效果
当请求缺少必填参数时,NestJS 自动返回 400 错误:
// 缺少 description 时
{
"statusCode": 400,
"message": ["description must not be empty"],
"error": "Bad Request"
}
json
// 缺少 amount 和 payer 时
{
"statusCode": 400,
"message": [
"amount must not be empty",
"payer must not be empty"
],
"error": "Bad Request"
}
json
测试请求示例
POST /api/v1/pay/order
{
"description": "测试商品",
"amount": {
"total": 100
},
"payer": {
"openid": "user_openid_here"
}
}
json
调试结果
断点调试可以看到最终生成的完整参数:
{
appid: "wx1234567890",
mchid: "1234567890",
description: "测试商品",
notify_url: "https://wechat-dev.domain.com/api/v1/pay/notify",
out_trade_no: "20260518143015001_2345678901", // 时间戳+分类ID+随机数
time_expire: "2026-05-18T15:00:15+08:00", // 30分钟后过期
amount: { total: 100 },
payer: { openid: "user_openid_here" }
}
text
401 错误:缺少 Authorization
发送请求后会收到 401 错误:
HTTP 头 authorization 值格式错误,请参考微信支付商户 REST API 签名规则
text
这是因为请求微信接口需要在 HTTP 头中添加 Authorization 签名信息。这是微信支付 APIv3 的认证机制,需要按照签名规则生成请求头。
下节将详细介绍 APIv3 的签名机制和 Authorization 头的生成步骤。
参考资源
- NestJS Validation - 参数校验
- class-validator - 验证装饰器
- 微信支付签名指南 - APIv3 签名规则
↑